#!/usr/bin/python
# -*- coding: UTF-8 -*-

from django.utils.deprecation import MiddlewareMixin


# class Md1(MiddlewareMixin):
#     def process_request(self,request):
#         print("Md1处理请求")
#
#     def process_response(self,request,response):
#         print("Md1返回响应")
#         return response
#
#     def process_view(self, request, view_func, view_args, view_kwargs):
#
#         print("Md1在执行%s视图前" %view_func.__name__)
#
#     def process_exception(self,request,exception):
#         print("Md1处理视图异常...")
#
# class Md2(MiddlewareMixin):
#
#     def process_request(self,request):
#         print("Md2处理请求")
#
#     def process_response(self,request,response):
#         print("Md2返回响应")
#         return response
#
#     def process_view(self, request, view_func, view_args, view_kwargs):
#
#         print("Md2在执行%s视图前" %view_func.__name__)
#
#     def process_exception(self,request,exception):
#         print("Md2处理视图异常...")


class Md1:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("Md1处理请求")

        response = self.get_response(request)

        print("Md1返回响应")

        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("Md1在执行%s视图前" % view_func.__name__)

    def process_exception(self, request, exception):
        print("Md1处理视图异常...")


class Md2:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        print("Md2处理请求")

        response = self.get_response(request)

        print("Md2返回响应")

        return response

    def process_view(self, request, view_func, view_args, view_kwargs):
        print("Md2在执行%s视图前" % view_func.__name__)

    def process_exception(self, request, exception):
        print("Md2处理视图异常...")


import sys
from django.views.debug import technical_500_response
from django.conf import settings


class DebugMiddleware():

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        response = self.get_response(request)

        return response

    def process_exception(self, request, exception):
        # 如果是管理员，则返回一个特殊的响应对象，也就是Debug页面
        # 如果是普通用户，则返回None，交给默认的流程处理
        if request.user.is_superuser or request.META.get('REMOTE_ADDR') in settings.ADMIN_IP:
            return technical_500_response(request, *sys.exc_info())


from django.http import HttpResponseForbidden


class BlackListMiddleware():

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        if request.META['REMOTE_ADDR'] in getattr(settings, "BLACKLIST", []):
            return HttpResponseForbidden('<h1>该IP地址被限制访问！</h1>')

        response = self.get_response(request)

        return response
